package org.turman.buobaobook.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.turman.buobaobook.component.ApplicationContextProvider;
import org.turman.buobaobook.model.entity.BookTask;
import org.turman.buobaobook.service.BookTaskService;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.List;

public class BookDownloadJob implements Job {
    private Logger logger = LoggerFactory.getLogger(BookDownloadJob.class);

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //通过applicationcontextprovider获取service bean
        BookTaskService bookTaskService = ApplicationContextProvider.getBean(BookTaskService.class);

        List<BookTask> bookTasks = bookTaskService.selectList();
        if (bookTasks != null && bookTasks.size() > 0) {
            bookTasks.stream().forEach(bookTask -> {
                logger.info("开始执行下载任务："+bookTask.getTaskName());
                if ("1".equals(bookTask.getTaskType())) {
                    Resource resource = new ClassPathResource(bookTask.getTaskFilePath());
                    try {
                        File tempFile = File.createTempFile("temp_", ".py");
                        Files.copy(resource.getInputStream(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                        String pythonCommand = "python " + tempFile.getAbsolutePath().trim();
                        if (null!=bookTask.getTaskParam() && !bookTask.getTaskParam().isEmpty()) {
                           pythonCommand += " "+ bookTask.getTaskParam().trim();
                        }

                        ProcessBuilder pb = new ProcessBuilder(pythonCommand.split(" "));
                        Process process = pb.start();
                        process.waitFor(); // 等待脚本执行完成

                        // 处理输出（这里简单打印，实际应用中可能需要更复杂的处理）
                        InputStream stdout = process.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
                        String line;
                        while ((line = reader.readLine()) != null) {
                            logger.info(line);
                        }
                        reader.close();

                        // 删除临时文件（根据需要调整）
                        tempFile.delete();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
}
